﻿using System;
using System.Collections;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;

using Coolite.Ext.Web;
using Excel = Microsoft.Office.Interop.Excel;
using EB = Sagacity.Entity.Build;
using Sagacity.NC.Web.FormForm;
using Sagacity.NC.Web.Form;

namespace Sagacity.NC.Form
{
    public partial class TabFormCommon : System.Web.UI.UserControl
    {
        /// <summary>
        /// 表单控件帮助类
        /// </summary>
        FormHelper helper = null;

        #region 定义列表表单属性


        /// <summary>
        /// 此表单是否只读
        /// </summary>
        public bool ReadOnly = false;
        /// <summary>
        /// 工具栏是否显示
        /// </summary>
        public bool projectTool = true;

        public ShowPlan ShowPlan { get; set; }

        /// <summary>
        /// 登陆人员信息
        /// </summary>
        public Sagacity.NC.Business.SysMange.FormUser CurrentUser { get; set; }

        /// <summary>
        /// 资源数据过滤条件
        /// </summary>
        private List<Sagacity.Entity.Query.FilterInfo> filters = new List<Sagacity.Entity.Query.FilterInfo>();
        public List<Sagacity.Entity.Query.FilterInfo> Filters { get { return filters; } set { filters = value; } }

        /// <summary>
        /// 需要添加的字段以及对应的值
        /// </summary>
        private Hashtable addFields = new Hashtable();
        public Hashtable AddFields { get { return addFields; } set { addFields = value; } }

        /// <summary>
        /// 当前Form对应的资源
        /// </summary>
        public int ResourceId { get; set; }

        /// <summary>
        /// 设置列表每页数据, 默认为0
        /// </summary>
        public int PageSize { get; set; }

        /// <summary>
        /// 当前Form表单操作表
        /// </summary>
        public string TableName { get; set; }

        /// <summary>
        /// 当前Form表单操作表的主键列名称
        /// </summary>
        public string TableKey { get; set; }

        /// <summary>
        /// 执行导入功能(默认为false)
        /// </summary>
        private bool sureImport = false;
        public bool SureImport { get { return sureImport; } set { sureImport = value; } }

        /// <summary>
        /// 执行导出功能(默认为false)
        /// </summary>
        private bool sureExport = false;
        public bool SureExport { get { return sureExport; } set { sureExport = value; } }


        /// <summary>
        /// 设置模型参数
        /// </summary>
        private List<Sagacity.Entity.Query.ParameterInfo> modelparams = new List<Sagacity.Entity.Query.ParameterInfo>();
        public List<Sagacity.Entity.Query.ParameterInfo> ModelParams { get { return modelparams; } set { modelparams = value; } }

        public int MenuId { get; set; }

        /// <summary>
        /// 人员类别
        /// </summary>
        public int ColFilterKey { get; set; }

        public string ColFilterIdentify { get; set; }

        FormExcelHelper fEHelper = null;

        public List<Coolite.Ext.Web.Observable> BtnControls = new List<Observable>();

        public bool ShowForm = true;

        public bool showDetailsColumn = true;

        /// <summary>
        /// 当前需要将选中数据加入到的观察窗的类型
        /// </summary>
        public ObserveType ObServeType = ObserveType.NoSet;

        private bool assoEnable = true;

        /// <summary>
        /// 是否显示关联操作按钮
        /// </summary>
        public bool AssoEnable
        {
            get
            {
                return assoEnable;
            }
            set
            {
                assoEnable = value;
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            fEHelper = new FormExcelHelper(ColFilterKey, ColFilterIdentify);           
            helper = new FormHelper(ColFilterKey, ColFilterIdentify, modelparams);
            helper.showForm = ShowForm;
            helper.showDetailsColumn = showDetailsColumn;
            helper.GroupFieldColor = "#DFE8F6";
            helper._currentUser = CurrentUser;
            
            if (!IsPostBack)
            {
                helper.showPlan = ShowPlan;
                hidResourceId.Value = ResourceId;
                
                GridShow();

                SetGridPanelPageSize();

                this.hidHasDetailColumn.Value = "true";
                this.btnExport.Visible = SureExport;
                this.btnImport.Visible = SureImport;
                
                InitBtnControls();
                InitMenu();
            }
        }

        /// <summary>
        /// 设置列表数据每页显示数量
        /// </summary>
        protected void SetGridPanelPageSize() 
        {
            if (PageSize == -1)
            {
                PagingToolBar1.PageSize = 100000;
            }
            else if (PageSize == 0)
            {
                PagingToolBar1.PageSize = 20;
            }
            else
            {
                PagingToolBar1.PageSize = PageSize;
            }
        }

        protected void InitBtnControls()
        {
            btnAsso.Visible = AssoEnable;

            if (ReadOnly)
            {
                this.btnAdd.Enabled = false;
                this.btnDel.Enabled = false;

                Coolite.Ext.Web.Button btnSave = winForm.FindControl("btnSaveDeteil") as Coolite.Ext.Web.Button;
                btnSave.Enabled = false;
            }

            Sagacity.Build.Role role = new Sagacity.Build.Role();
            List<EB.ModuleItemInfo> ms = role.GetModuleItemInfos(CurrentUser.LoginRole).FindAll(o => o.ParentId ==
                MenuId && o.State == 0).ToList();

            foreach (Coolite.Ext.Web.Observable c in BtnControls) 
            {
                EB.ModuleItemInfo m = ms.Find(o => o.Name == c.ID);

                if (m != null) 
                {
                    projectToolbar.Items.Add(c);
                }
            }
            SetButtonRight(ms);
            this.projectToolbar.Visible = projectTool;
        }

        protected void InitMenu() 
        {
            hidSqlCases.Value = helper.InitSqlCase(tbSqlCase, ResourceId, winSqlForm, MenuSelfUpdate);


            if (ObServeType == ObserveType.NoSet || ObServeType == ObserveType.OthersObserve)
            {
                RowContextMenu.Visible = false;
                return;
            }

            List<Sagacity.Entity.Query.FilterInfo> filters = new List<Sagacity.Entity.Query.FilterInfo>();
            filters.Add(new Sagacity.Entity.Query.FilterInfo("OwnerId", "=", CurrentUser.Id));

            RowContextMenu.Visible = true;
            int observeRId = int.Parse(hidPersonObserveRId.Value);
            DataTable dtObserves = Sagacity.NC.Business.SysMange.Common.GetRoleRightData(CurrentUser.LoginRole, observeRId,filters);
            foreach (DataRow r in dtObserves.Rows) 
            {
                Coolite.Ext.Web.MenuItem item = new Coolite.Ext.Web.MenuItem();
                item.Icon = Icon.Pencil;
                item.Text = r["VIEWNAME"].ToString();
                item.Listeners.Click.Handler = string.Format("javascript:addObserve({0})",r["VIEWID"].ToString());
                MenuAddObserve.Items.Add(item);
            }            
        }

        [AjaxMethod]
        public string AddObserve(int viewId,int dataId) 
        {
            List<Sagacity.Entity.Query.FilterInfo> filters = new List<Sagacity.Entity.Query.FilterInfo>();
            filters.Add(new Sagacity.Entity.Query.FilterInfo("ViewId","=",viewId));
            filters.Add(new Sagacity.Entity.Query.FilterInfo("DataId","=",dataId));            
            
            int observeRId = 0;
            if(ObServeType == ObserveType.PersonObserve)
                observeRId = int.Parse(hidPersonObserveDetailRId.Value);

            DataTable dtObserves = Sagacity.NC.Business.SysMange.Common.GetRoleRightData(CurrentUser.LoginRole, observeRId,filters);
            string msg = string.Empty;
            if (dtObserves.Rows.Count > 0)
                return "该观察窗已存在此人员！$False";
            else
            {
                bool result = helper.mCommon.AddObserveInfo(observeRId, viewId, dataId,ref msg);
                return msg + "$" + result.ToString();
            }
        }

        /// <summary>
        /// 针对页面中按钮权限的操作
        /// </summary>
        protected void SetButtonRight(List<EB.ModuleItemInfo> ms)
        {
            if (MenuId == 0)
                return;            

            foreach (EB.ModuleItemInfo mInfo in ms)
            {
                Control control = FindControl(mInfo.Name);
                if (control != null)
                    control.Visible = true;
            }

            this.btnSave.Visible = this.btnImport.Visible;
            this.btnRefresh.Visible = this.btnImport.Visible;
        }

        /// <summary>
        /// 设置使用指定JS字符串数据封装的过滤信息
        /// </summary>
        private void SetJSFilters()
        {
            #region 设置js过滤信息

            if (hidInterfaceFilters.Value.ToString() != "")
            {
                string[] strfilter = hidInterfaceFilters.Value.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strfilter)
                {
                    string[] filter = str.Split(new string[] { "$" }, StringSplitOptions.RemoveEmptyEntries);

                    Sagacity.Entity.Query.FilterInfo f = filters.Find(o => o.FieldName.ToUpper() == filter[0].ToUpper());
                    if (f != null)
                        filters.Remove(f);
                    filters.Add(new Sagacity.Entity.Query.FilterInfo(filter[0], filter[1], filter[2]));
                }
            }

            #endregion
        }

        protected void Store_Refresh(object sender, StoreRefreshDataEventArgs e)
        {
            GridShow();
            if (sureImport == true && IsPostBack)
            {
                this.btnAdd.Enabled = true;
                this.btnDel.Enabled = true;
                this.btnExport.Enabled = true;
                this.btnImport.Enabled = true;
                this.btnSave.Enabled = false;

                if (this.hidHasDetailColumn.Value.ToString() == "false")
                {
                    XmlDocument xml = new XmlDocument();
                    
                    xml.LoadXml(hidXML.Value.ToString());
                    int count = xml.SelectNodes("Root/Fields/Field[@IsHidden='False']").Count;
                    InsertColumn(count + 2);
                    this.hidHasDetailColumn.Value = true;
                }
            }
        }

        /// <summary>
        /// 取得资源数据查询配置信息
        /// </summary>
        /// <returns></returns>
        [AjaxMethod]
        public string GetDataQueryCnf() 
        {
            SetJSFilters();

            string cnfStr = string.Empty;
            string filterstr = string.Empty;
            string parameterstr = string.Empty;

            foreach (Sagacity.Entity.Query.FilterInfo f in filters) 
            {
                filterstr += f.FieldName+"$"+f.FieldCondition+"$"+f.FieldValue+";";
            }

            foreach (Sagacity.Entity.Query.ParameterInfo p in modelparams) 
            {
                parameterstr += p.ParameterName + "$" + p.RealValue + ";";
            }

            return cnfStr = "Filters=" + filterstr + "&Params=" + parameterstr;
            //return Sagacity.Common.DES.Encode(cnfStr, Config.BaseConfig.Instance.AES_EncryptKey);
        }

        /// <summary>
        /// 获取保存在HidXML中的数据
        /// </summary>
        [AjaxMethod]
        public string SubmitForm()
        {
            bool excuteResult = false;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(hidXML.Value.ToString());

            foreach (string key in AddFields.Keys) 
            {
                XmlNode n = doc.SelectSingleNode("Root/Fields/Field[@Name='"+key+"'][@AddField='True']");
                n.Attributes["Value"].Value = AddFields[key].ToString();
            }

            string keyId = "0";
            string msg = string.Empty;
            if (helper.SaveTableInfo(doc, true, hidSelects.Value.ToString(),out keyId,ref msg))
            {
                GridShow();
                excuteResult = true;
            }
            if (excuteResult)
                msg = "执行成功！";
            else if(excuteResult == false && msg == string.Empty)
                msg = "执行失败！";
            return excuteResult.ToString() + "$"+ msg;
        }

        [AjaxMethod]
        public void GetModelFilterResult(int modelId)
        {
            helper._filterModelId = modelId;
            GridShow();
        }

        public void GridShow()
        {
            SetJSFilters();
            string[] tableInfo = Sagacity.NC.Business.SysMange.Common.GetKeyByResourceId(ResourceId);
            hidKey.Value = tableInfo[1].ToUpper();
            string fieldInfo = "";
            helper.SetGridEditInfo(CurrentUser.LoginRole, ResourceId, GridPanel1, Store1, Filters,
                tableInfo[1].ToUpper(), this.winForm, this.pnlForm.Controls, out fieldInfo, !IsPostBack, this.otherContent);

            if (!IsPostBack)
            {
                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                builder.Append("<Root>");
                builder.Append("<TableInfo Name='" + tableInfo[0].ToUpper() + "' CurrentExcuteSate='0' KeyName='" + tableInfo[1].ToUpper() + "' CurrentUser='" + CurrentUser.Id + "' Resource='" + ResourceId + "' Log='true' />");
                builder.Append("<RuleFilter DataId='' Type='' />");
                builder.Append(fieldInfo);
                builder.Append("</Root>");

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(builder.ToString());
                if(Filters.Count != 0)
                    hidSelects.Value = Filters[0].FieldValue + "$";

                XmlNode fields = doc.SelectSingleNode("Root/Fields");
                foreach (string f in AddFields.Keys)
                {
                    fields.InnerXml += "<Field Name='" + f + "' ControlType='' IsHidden='True' EnableEdit='False' AddField='True' Value='" + AddFields[f].ToString() + "'/>";
                }

                hidXML.Value = doc.InnerXml;
            }
        }

        protected void UpImport(object sender, AjaxEventArgs e)
        {
            if (ulImport.HasFile == false)
            {
                Ext.Msg.Alert("注意", "请选择需要导入的文件。").Show();
                return;
            }
            string IsXls = System.IO.Path.GetExtension(ulImport.FileName).ToString().ToLower();
            if (IsXls != ".xls")
            {
                Ext.Msg.Alert("注意", "只可以选择Excel文件。").Show();
                return;
            }

            string filename = DateTime.Now.ToString("yyyymmddhhMMss") + ulImport.FileName;
            string savePath = Server.MapPath(("~\\UpFiles\\") + filename + ".xls");
            ulImport.SaveAs(savePath);

            try
            {
                Sagacity.Entity.Build.ResourceInfo resource = (new Sagacity.Build.Application.Resource()).GetResrouse(ResourceId);
                DataTable dt = fEHelper.GetExcelTable(savePath, 1);
                for (int i = dt.Columns.Count - 1; i >= 0; i--)
                {
                    Sagacity.Entity.Build.QueryFieldInfo f = resource.Fields.Find(o => o.FieldCaption.Replace(" ", "") == dt.Rows[0][i].ToString().Replace(" ", ""));
                    if (f == null)
                        dt.Columns.RemoveAt(i);
                    else
                        dt.Columns[i].ColumnName = f.FieldName;
                }

                if (dt.Columns.Count < resource.Fields.FindAll(o => o.IsEnableEdit == true).Count)
                {
                    Ext.Msg.Alert("注意", "Excle表导入失败，数据格式不满足要求。").Show();
                    return;
                }

                dt.Rows.RemoveAt(0);
                helper.SetStore(resource.Fields, this.Store1, TableKey);
                this.Store1.DataSource = dt;
                this.Store1.DataBind();
                this.GridPanel1.RemoveColumn(resource.Fields.FindAll(o => o.IsHidden == false).Count + 2);
                this.hidHasDetailColumn.Value = "false";
                Ext.Msg.Alert("注意", "导入成功! 当前显示为导入数据，请确认并保存，否则请刷新。").Show();
                this.btnExport.Enabled = false;
                this.btnSave.Enabled = true;
                this.btnAdd.Enabled = false;
                this.btnDel.Enabled = false;
            }
            catch
            {
                Ext.Msg.Alert("注意", "Excle表导入失败，请检查你的格式。").Show();
            }
        }

        /// <summary>
        /// 提交并保存数据
        /// </summary>
        protected void Store1_Submit(object sender, StoreSubmitDataEventArgs e)
        {
            XmlNode xml = e.Xml;
            if (fEHelper.SaveImportData(e.Xml, hidXML.Value.ToString(), AddFields))
            {
                this.GridPanel1.Reload();
                Ext.Msg.Alert("注意", "执行成功!").Show();
                return;
            }
            Ext.Msg.Alert("注意", "保存失败!请检查你的数据。").Show();
        }

        /// <summary>
        /// 添加链接列
        /// </summary>
        /// <param name="position">位置</param>
        protected void InsertColumn(int position)
        {
            Column linkColumn = new Column();
            linkColumn.Renderer.Fn = "Form$DetailsRender";
            linkColumn.ColumnID = "Details";
            linkColumn.Width = 35;

            this.GridPanel1.InsertColumn(position, linkColumn);
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        public void ToExcel(object sender, EventArgs e)
        {
            SetJSFilters();
            fEHelper.OutPutExcel(CurrentUser.LoginRole, this.ResourceId, this.Filters, this.Response, Server.MapPath("../../ExcelTempDir/ResourceTemp.xml"), modelparams);
        }


        /// <summary>
        /// 执行Sql方案
        /// </summary>
        /// <param name="exsqlcases"></param>
        /// <returns></returns>
        [AjaxMethod]
        public string ExcuteSqlCases(string exsqlcases)
        {
            string[] sqlcaseIdstrs = exsqlcases.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            int[] sqlcaseIds = new int[sqlcaseIdstrs.Length];
            for (int i = 0; i < sqlcaseIdstrs.Length; i++)
            {
                sqlcaseIds[i] = int.Parse(sqlcaseIdstrs[i]);
            }
            return helper.ExcuteSqlCase(sqlcaseIds);
        }

        [AjaxMethod]
        public string NodeLoad(string nodeID, int fieldId, string nodeClickHandler)
        {
            return helper.NodeLoad(nodeID, fieldId,false,nodeClickHandler);
        }

        /// <summary>
        /// 取得关联字段的数据
        /// </summary>
        /// <param name="controlType"></param>
        /// <param name="fieldId"></param>
        /// <returns></returns>
        [AjaxMethod]
        public string GetFieldAssoDataInfo(string controlType,int fieldId,string paramName,string paramValue) 
        {
            return helper.GetFieldAssoDataInfo(controlType,fieldId, paramName, paramValue);
        }
    }
}